<template>
    <view class="container">
        <!-- 顶部分类选项 -->
        <view class="tabs">
            <view v-for="(tab, index) in tabs" :key="index" class="tab" :class="{ active: index === activeTab }"
                @click="selectTab(index)">
                {{ tab.name }}
            </view>
        </view>

        <!-- 学习资源列表 -->
        <view v-for="(item, index) in resources" :key="index" class="resource-card" @click="learnNow(item)">
            <image :src="`/img`+item.img" mode="aspectFill" class="resource-image"></image>
            <view class="resource-info">
                <view class="resource-title">{{ item.name }}</view>
                <view class="resource-description" :title="item.description">{{ truncateDescription(item.description) }}</view>
                <!-- 获取到id跳转 -->
                <view class="resource-footer">
                    <text class="resource-people">{{ item.num }} 次学习</text>
                    <button class="learn-button">立即学习</button>
                </view>
            </view>
        </view>
        <!-- 下拉加载提示 -->
        <view v-if="loading" class="loading">加载中...</view>
        <view v-if="noMore" class="no-more">没有更多数据了</view>
    </view>
</template>

<script>
import {
    ref,
    computed,
    onMounted,
    onUnmounted,
    onActivated
} from 'vue';
import {
    logdata,
    study,
    studynum
} from '@/common/api.js';
import {
    useUserStore
} from '@/stores/user.js';

export default {
    setup() {
        // 用户数据
        const userStore = useUserStore();
        const searchQuery = ref(''); // 搜索框输入

        // 定义分页响应式变量
        const page = ref({
            size: 7,
            currentPage: 1
        });

        // 是否正在加载数据
        const isLoading = ref(false);
        // 是否已经加载完所有数据
        const noMore = ref(false); 
        // 假设的日志记录数据
        const logs = ref([]);
        
        // 顶部分类选项
        const tabs = ref([
            { name: '全部', status: 0 },
            { name: '施肥知识', status: 1 },
            { name: '打药知识', status: 2 },
            { name: '种植知识', status: 3 }
        ]);
        const activeTab = ref(0);

        const currentPage = ref(1); // 当前页码
        const size = ref(7); // 每页加载的数据条数
        const loading = ref(false); // 是否正在加载数据
        const resources = ref([]); // 学习资源数据

        // 计算属性来过滤日志记录
        const filteredLogs = computed(() => {
            if (searchQuery.value) {
                return logs.value.filter(
                    (log) =>
                        log.operation.includes(searchQuery.value) ||
                        String(log.logId).includes(searchQuery.value)
                );
            } else {
                return logs.value;
            }
        });

        // 日志数据请求函数
        const logselect = async (params) => {
            if (isLoading.value || noMore.value) return;

            isLoading.value = true;
            try {
                const res = await logdata(params);
                if (res.code === 200) {
                    logs.value = [...logs.value, ...res.data];
                    if (res.data.length < page.value.size) {
                        noMore.value = true;
                    }
                }
            } catch (error) {
                console.error('请求失败:', error);
            } finally {
                isLoading.value = false;
            }
        };

        // 获取学习资源的方法
        const fetchResources = async (params) => {
            if (loading.value || noMore.value) return;

            loading.value = true;
            try {
                const response = await study(params);

                if (response && response.data) {
                    if (response.data.length < size.value) {
                        noMore.value = true; // 数据不足，说明没有更多数据
                    }
                    resources.value.push(...response.data);
                } else {
                    console.error('数据获取失败');
                }
            } catch (error) {
                console.error('请求失败:', error);
            } finally {
                loading.value = false;
            }
        };

        // 重置数据并请求资源
        const resetAndFetchResources = (status) => {
            currentPage.value = 1; // 重置页码
            resources.value = []; // 清空现有数据
            noMore.value = false; // 重置是否还有更多数据
            fetchResources({ currentPage: currentPage.value, size: size.value, status });
        };

        // 立即学习按钮的点击事件
        const learnNow = (item) => {
            const params = {
                plantId: item.plantId,
                num: item.num + 1
            };
            studynum(params).then(() => {
                wx.redirectTo({
                    url: `/pages/study/Detail?id=${item.plantId}`
                });
            });
        };

        // 页面挂载时的初始化
        onMounted(() => {
            // 初始加载日志数据
            const params = {
                size: page.value.size,
                currentPage: page.value.currentPage,
                userId: userStore.userId,
            };
            logselect(params);
            // 初始加载学习资源数据
            resetAndFetchResources(tabs.value[activeTab.value].status);
        });

        // 页面激活时刷新学习资源数据
        onActivated(() => {
            resetAndFetchResources(tabs.value[activeTab.value].status);
        });

        // 页面卸载时清理逻辑
        onUnmounted(() => {
            // 在页面卸载时执行一些清理操作
        });

        // 下拉刷新处理函数
        const onPullDownRefresh = () => {
            // 重置日志数据
            page.value.currentPage = 1;
            logs.value = [];
            noMore.value = false;

            const params = {
                size: page.value.size,
                currentPage: page.value.currentPage,
                userId: userStore.userId,
            };
            logselect(params).then(() => {
                uni.stopPullDownRefresh();
            });
        };

        // 微信小程序中的上拉加载更多处理函数
        const onReachBottom = () => {
            console.log("触底事件触发");
            if (!noMore.value) {
                page.value.currentPage += 1; // 增加页码
                fetchResources({
                    currentPage: page.value.currentPage,
                    size: size.value,
                    status: tabs.value[activeTab.value].status,
                });
            }
        };

        // 截断描述文字，最多显示一行并以省略号结尾
        const truncateDescription = (description) => {
            return description.length > 10 ? description.slice(0, 15) + '...' : description;
        };

        // 切换选项卡
        const selectTab = (index) => {
            activeTab.value = index;
            resetAndFetchResources(index);
        };

        return {
            page,
            logs,
            isLoading,
            noMore,
            searchQuery,
            filteredLogs,
            logselect,
            onPullDownRefresh,
            onReachBottom,
            tabs,
            activeTab,
            currentPage,
            size,
            loading,
            resources,
            selectTab,
            learnNow,
            truncateDescription,
        };
    },

    // 注册小程序的生命周期函数
    onReachBottom() {
        this.onReachBottom();
    },
    onPullDownRefresh() {
        this.onPullDownRefresh();
    }
};
</script>




<style scoped>
/* 样式代码，根据实际设计调整 */
.resource-list {
    height: 100vh;
}

.loading,
.no-more {
    text-align: center;
    padding: 16px;
}

.container {
    height: 100vh;
    /* 确保容器高度是视口的高度 */
    overflow-y: auto;
    /* 使得容器内容可以上下滚动 */
    padding: 16px;
    /* 可选：增加一点内边距，使内容不至于紧贴边缘 */
    box-sizing: border-box;
}

.tabs {
    display: flex;
    background-color: #fff;
    padding: 10rpx;
    margin-bottom: 20rpx;
    border-bottom: 1rpx solid #e5e5e5;
}

.tab {
    flex: 1;
    text-align: center;
    padding: 15rpx 0;
    font-size: 30rpx;
    color: #333;
    transition: color 0.3s ease, border-bottom-color 0.3s ease;
    position: relative;
}

.tab.active {
    color: #39b54a;
    /* 绿色，表示选中状态 */
    font-weight: bold;
}

.tab.active::after {
    content: "";
    position: absolute;
    left: 20%;
    bottom: 0;
    width: 60%;
    height: 4rpx;
    background-color: #39b54a;
    /* 下划线颜色 */
    border-radius: 2rpx;
}

.resource-card {
    display: flex;
    background-color: #fff;
    margin-bottom: 20rpx;
    border-radius: 10rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
    /* 增加阴影效果 */
}

.resource-image {
    width: 160rpx;
    height: 200rpx;
	margin: auto;
    margin-right: 20rpx;
	border-radius: 5px;
}

.resource-info {
    flex: 1;
    padding: 10rpx 0;
}

.resource-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
}

.resource-description {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 10rpx;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.resource-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.resource-people {
    font-size: 24rpx;
    color: #999;
}

.learn-button {
    margin-left: 100px;
    background-color: #39b54a;
    color: #fff;
    padding: 10rpx 20rpx;
    border-radius: 15rpx;
    font-size: 28rpx;
}
</style>
